package queue;

/**
 * 环形队列
 */
public class CircleArrayQueue {
    private int maxSize; //最大容量
    private int front;  //队列头
    private int rear;   //队列尾
    private int[] arr;  //存放数据，模拟队列

    //创建队列的构造器
    public CircleArrayQueue(int arrMaxSize){
        maxSize=arrMaxSize;
        arr=new int[maxSize];
        front=0;
        rear = 0;
    }

    //判断是否为满
    public boolean isFull(){
        return (rear+1)%maxSize == front;
    }

    //是否为空
    public boolean isEmpty(){
        return rear==front;
    }

    //添加数据到队列
    public void addQueue(int n){
        if (isFull()){
            System.out.println("队列满，不能添加");
            return;
        }
        arr[rear]=n;
        rear=(rear+1)%maxSize;
    }

    //取数据
    public int getQueue(){
        if (isEmpty()){
            throw new RuntimeException("队列为空，不能取数据");
        }
        int value=arr[front];
        front=(front + 1)%maxSize;
        return value;
    }

    //显示数据
    public void showQueue(){
        if (isEmpty()){
            System.out.println("没有数据，队列为空");
            return;
        }
        for (int i = front; i < front+size(); i++){
            System.out.printf("arr[%d]=%d\n",i % maxSize,arr[i % maxSize]);
        }
    }

    //当前有效个数
    public int size(){
        return (rear+maxSize-front) % maxSize;
    }

    //显示队列头
    public int headQueue() {
        if (isEmpty()){
            throw new RuntimeException("队列为空，没有数据");
        }
        return arr[front];
    }
}
